package com.sky.aspect;


import com.sky.anno.CleanCache;
import com.sky.enumeration.CleanCacheType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Set;

@Aspect
@Component
@Slf4j
public class CleanCacheAspect {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Pointcut("execution(* com.sky.controller.admin.DishController.*(..)) && @annotation(com.sky.anno.CleanCache)")
    public void cleanCachePointCut() {
    }

    @Before("cleanCachePointCut()")
    public void cleanCache(JoinPoint joinPoint) throws NoSuchFieldException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        CleanCache annotation = signature.getMethod().getAnnotation(CleanCache.class);
        //获得注解的类型值
        CleanCacheType value = annotation.value();
        log.info("清理缓存类型：{}", value);
        Object[] args = joinPoint.getArgs();

        if (args == null || args.length == 0) {
            return;
        }

        if (value == CleanCacheType.ADD) {
            //添加类型
            //先获得分类id
            try {
                Object entity = args[0];
                Field categoryId = entity.getClass().getDeclaredField("categoryId");
                categoryId.setAccessible(true);
                Long id = (Long) categoryId.get(entity);
                String key = "dish_" + id;
                log.info("根据分类id删除缓存：{}", key);
                redisTemplate.delete(key);

            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        } else {
            //其它类型的 直接删除所有的key
            Set<String> keys = redisTemplate.keys("dish_*");
            if (!keys.isEmpty()) {
                redisTemplate.delete(keys);
            }

        }
    }


}
